const router = require('koa-router')();
const websockify = require('koa-websocket');
const Koa = require('koa');
const { ChatMsg, AttentionMsg } = require('./src/utils/Message')
const RoomKeeper = require('./src/utils/RoomKeeper')
const WsController = require('./src/controllers/message')
const fs = require('fs')

const app = websockify(new Koa());

router.get('/', async (ctx) => {
    console.log('???', ctx)
    ctx.response.set('Content-Type', 'text/html')
    ctx.body = fs.readFileSync('./example/index.html')
})

router.get('/ws-chat', async (ctx) => {
    ctx.websocket.send(AttentionMsg('log', { text: '链接成功，您已进入/房间' }));

    RoomKeeper.rooms['/'].checkin(ctx.websocket)

    ctx.websocket.on('message', (message) => {
        WsController(ctx.websocket, message)
    });
    ctx.websocket.on('close', (message) => {
        RoomKeeper.rooms['/'].list.delete(ctx.websocket)
        console.log('close', RoomKeeper.rooms['/'].list);
    });
});


app.ws.use(router.routes()).use(router.allowedMethods());
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);